package mail;


import java.io.UnsupportedEncodingException;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;


/**
 * 
 * @date 2013-8-1 下午2:47:43
 */
public class EmailSender {
	

	
	private static String host = "mail.iqiyi.com";
	private static String username = "tp_alert";
	private static String password = "8ik,/;p0";
	private static String mailFrom = "tp_alert@qiyi.com";
	public static String mailNick = "QIM";

	private EmailSender() {
	}

	public static boolean sendEmail(String toEmail, String title, String content) throws MessagingException, UnsupportedEncodingException {		
		try {
			String to = toEmail;
			String subject = title;
			String messageText = content;

			java.util.Properties props = new java.util.Properties();
			props.setProperty("mail.smtp.auth", "true");// 指定是否需要SMTP验证
			props.setProperty("mail.smtp.host", host);// 指定SMTP服务器
			props.put("mail.smtp.timeout", "25000");
			props.put("mail.transport.protocol", "smtp");
			Session mailSession = Session.getDefaultInstance(props);

			// Step 2: Construct the message
			String nick = javax.mail.internet.MimeUtility.encodeText(mailNick);
			InternetAddress fromAddress = new InternetAddress(nick +"<" + mailFrom + ">");
			InternetAddress toAddress = new InternetAddress(to);

			MimeMessage mimeMessage = new MimeMessage(mailSession);
			mimeMessage.setFrom(fromAddress);
			mimeMessage.addRecipient(javax.mail.Message.RecipientType.TO, toAddress);
			mimeMessage.setSentDate(new java.util.Date());
			mimeMessage.setSubject(MimeUtility.encodeText(subject, "utf-8", "B"));
			mimeMessage.setContent(messageText, "text/html;charset=utf-8");

			// Step 3:send
			Transport transport = mailSession.getTransport("smtp");
			transport.connect(username,password);
			transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
			transport.close();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	

	

	
	public static void main(String[] args) {	
		try {
			Boolean bln = sendEmail("guoenzhou@qiyi.com", "测试标题", "测试内容");
			System.out.println(bln);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	
	}
}
